import logging

from django.db.models import F
from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache
from django.db import transaction

from bk_framework_app.models import ApiRequestCount
from bk_framework_app.tasks import record_api_request
from blueking.component.base import logger


logger = logging.Logger(__name__)
# CMDB模块的接口
CMDB_BEHAVIORS = [
    'biz-list',
    'set-list',
    'module-list',
    'host-list',
    'host-detail'
]
# JOB模块的接口
JOB_BEHAVIORS = [
    'search-file',
    'backup-file',
    'backup-record'
]


class RecordUserBehaviorMiddleware(MiddlewareMixin):
    """
    定义自定义中间件,用于记录用户行为
    """

    def process_request(self, request):
        """
        在请求进入视图之前调用
        :param request: Django请求对象
        :return: None
        """
        try:
            api_name = request.path.split("/")[-2]
            logger.debug(f"Processing API request: {api_name}")

            api_category = "CMDB" if api_name in CMDB_BEHAVIORS \
                else "JOB" if api_name in JOB_BEHAVIORS \
                else "unknown"
            record_api_request.delay(api_name , api_category)
        except Exception as e:
            logger.error(f"Error processing API request: {e}")
        return None

